package aspect;

import java.math.BigInteger;
import java.security.MessageDigest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import pojo.TestUser;

@Component
@Aspect
public class PasswordEncryptAspect {
	private final String LOGIN_POINTCUT = "execution(* service.TestUserManager.loginUser(..))";
	private final String REGISTER_POINTCUT = "execution(* service.TestUserManager.addUser(..))";
	
	@Around(value=LOGIN_POINTCUT)
	public Object loginAround(ProceedingJoinPoint point) {
		Object o = null;
		Object[] args = point.getArgs();
		String passwd = args[1].toString();
		
		try {
			// MD5 encrypt
			MessageDigest md = MessageDigest.getInstance("MD5");
			String enc = new BigInteger(1, md.digest(passwd.getBytes())).toString(16);
			args[1] = enc;
			o = point.proceed(args);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	
	@Around(value=REGISTER_POINTCUT)
	public Object registerAround(ProceedingJoinPoint point) {
		Object o = null;
		Object[] args = point.getArgs();
		TestUser u = (TestUser) args[0];
		
		try {
			// MD5 encrypt
			MessageDigest md = MessageDigest.getInstance("MD5");
			String enc = new BigInteger(1, md.digest(u.getPasswd().getBytes())).toString(16);
			u.setPasswd(enc);
			o = point.proceed(new Object[] {u});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
}
